<template>
  <el-main class="user-userinfo">
    <div>
      <el-avatar :size="100" style="font-size: 200%">{{avatar}}</el-avatar>
    </div>
    <el-form :model="userInfo" :disabled="disabled">
      <div class="row">
        <el-form-item class="col-sm-6" label="姓名">
          <el-input v-model="userInfo.realName"></el-input>
        </el-form-item>
        <el-form-item class="col-sm-6" label="用户id">
          <el-input v-model="userInfo.id" disabled></el-input>
        </el-form-item>
      </div>
      <div class="row form-select">
        <el-form-item  class="col-sm-6" label="性别">
          <br/>
<!--          <el-input v-model="userInfo.sex"></el-input>-->
          <el-select v-model="userInfo.sex" style="width: 100%">
            <el-option value="女"></el-option>
            <el-option value="男"></el-option>
          </el-select>
        </el-form-item >
        <el-form-item  class="col-sm-6" label="年龄">
          <el-input v-model="userInfo.age"></el-input>
        </el-form-item >
      </div>
      <el-form-item label="身份证号">
        <el-input v-model="userInfo.idCard"></el-input>
      </el-form-item >
    </el-form>
    <div class="edit-button">
      <el-button type="primary" @click.stop="editUserInfo">{{btnTitle}}</el-button>
      <el-button v-show="!disabled" @click.stop="cancelEdit">取消</el-button>
    </div>
  </el-main>
</template>
<script>
import api from "@/apis/api"
export default {
  data(){
    return {
      userInfo:{},
      disabled: true
    }
  },
  computed:{
    avatar(){
      const name = this.$store.state.userModules.userInfo.realName
      const nameList = String(name).split('')
      return nameList[nameList.length - 2] + nameList[nameList.length - 1]
    },
    btnTitle(){
      return this.disabled?"编辑":"保存"
    }
  },
  methods:{
    cancelEdit(){
      this.disabled = true
      this.infoInit()
    },
    async editUserInfo() {
      if (!this.disabled) {
        const userinfo = this.$util.jsonToParse(this.userInfo)
        userinfo.sex = userinfo.sex === "女"?0:"1"
        const result = await api.reviseUserInfo(userinfo)
        if (result.code === 200){
          this.$util.successMessage("修改成功")
          await this.$store.dispatch("setUserInfo")
        }else{
          this.$util.errorMessage(result.msg)
          return null
        }
      }
      this.infoInit()
      this.disabled = !this.disabled
    },
    infoInit(){
      const data = this.$util.jsonToParse(this.$store.state.userModules.userInfo)
      data.sex = data.sex === 0?"女":"男"
      this.userInfo = data
    }
  },
  mounted() {
    this.infoInit()
  }
}
</script>

